<template>
  <div class="table-container">
    <a-card class="mb-3" :bordered="false">
      <div class="flex justify-between">
        <div class="flex gap-2">
          <a-button type="primary" @click="draw()">
            {{ t["新增"] }}
          </a-button>
          <a-button @click="getList">
            {{ t["刷新"] }}
          </a-button>
        </div>
        <div class="flex">
          <div class="flex gap-2 item-center">
            <Scope v-model="query.scope" style="width: 160px" @change="getList"> </Scope>
            <a-input-search
              v-model="query.templateName"
              search-button
              :placeholder="t['请输入模板名称']"
              allow-clear
              @keydown.enter="search"
              @search="search"
              class="h-fit"
            ></a-input-search>
          </div>
          <a-divider direction="vertical" class="h-full"></a-divider>
          <XDelete :disabled="selectedKeys.length <= 0" @ok="delSelectItems" />
        </div>
      </div>
    </a-card>

    <a-card :bordered="false">
      <a-table
        v-model:selectedKeys="selectedKeys"
        column-resizable
        page-position="bottom"
        :columns="translateColumns(columns)"
        :data="tableData"
        :loading="loading"
        :row-selection="{
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false
        }"
        :bordered="false"
        size="medium"
        row-key="templateId"
        :pagination="{
          pageSize: query.pageSize,
          total: query.total,
          current: query.pageNum,
          showJumper: true,
          showPageSize: true,
          showTotal: true
        }"
        @filter-change="filterChange"
        @page-change="pageChange"
        @page-size-change="pageSizeChange"
      >
        <template #index="{ rowIndex }">
          <span>{{ rowIndex + 1 }}</span>
        </template>
        <template #imgSrc="{ record }">
          <a-image :preview="false" :width="100" :height="60" :src="record.imgSrc" fit="contain" />
        </template>
        <template #optional="{ record }">
          <div class="flex gap-2 w-full items-center">
            <template v-if="record.share === '1'">
              <a-link @click="copy(record.templateId)">
                {{ t["复制"] }}
              </a-link>
              <a-divider direction="vertical" />
            </template>

            <a-link @click="draw(record)">
              {{ t["绘制"] }}
            </a-link>
            <a-divider direction="vertical" />
            <a-link @click="editTemplate(record)">
              {{ t["编辑"] }}
            </a-link>
            <a-divider direction="vertical" />
            <XDelete @ok="delSelectItems(record.templateId)">
              <IconDelete />
            </XDelete>
          </div>
        </template>

        <template #major="{ record }">
          <Major :major="record.major"></Major>
        </template>

        <template #share="{ record }">
          <template v-if="Number(record.share) === 0">
            <icon-stop style="color: red" />
          </template>

          <template v-else>
            <icon-share-alt style="color: green" />
          </template>
        </template>
        <template #templateId="{ record }">
          <a-tooltip :content="record.templateId">
            <div class="flex items-center" @click="copyText(record.templateId)">
              <div>...{{ record.templateId.slice(10, 18) }}</div>
              <IconCopy></IconCopy>
            </div>
          </a-tooltip>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="modelBox"
      draggable
      :footer="false"
      :title="t['操作']"
      width="800px"
      @close="resetForm"
    >
      <a-form :model="form" auto-label-width @submit-success="saveOrUpdate">
        <a-form-item
          field="templateName"
          :label="t['模板名称']"
          :rules="{
            required: true,
            minLength: 2,
            maxLength: 50,
            message: t['校验失败']
          }"
        >
          <a-input v-model.trim="form.templateName" />
        </a-form-item>

        <a-form-item field="time" :label="t['闪灯次数']">
          <a-input-number :min="0" v-model="form.times"></a-input-number>
        </a-form-item>
        <!-- <a-form-item field="time" :label="t['闪灯频率']">
          <a-input-number :min="0" v-model="form.frequency"></a-input-number>
        </a-form-item> -->

        <a-form-item field="time" :label="t['闪灯颜色']">
          <a-radio-group
            :options="translateOptions(lightColor)"
            v-model="form.light"
          ></a-radio-group>
        </a-form-item>

        <a-form-item field="templateColor" :label="t['模板颜色']">
          <a-radio-group
            v-model="form.templateColor"
            :options="translateOptions(deviceColorList)"
            :disabled="true"
          />
        </a-form-item>

        <a-form-item field="major" :label="t['模式']">
          <a-radio-group v-model="form.major">
            <a-radio v-for="(item, key) in majorList" :key="key" :value="item.value">
              {{ t[item.label] }}
            </a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item field="templateColor" :label="t['是否共享']">
          <a-radio-group v-model="form.share" :options="translateOptions(isList)"></a-radio-group>
        </a-form-item>

        <a-form-item field="name" :label="t['价签尺寸']" :disabled="!!form.templateId">
          <a-select v-model="form.resolutionId">
            <a-option v-for="(item, key) in resolutionList" :key="key" :value="item.value">
              {{ item.label }}
            </a-option>
          </a-select>
        </a-form-item>

        <a-form-item
          v-if="form.major === ENUM_MAJOR.MAIN"
          field="templateColor"
          :label="t['关联模板']"
        >
          <DynamicField :refTemplateOptions="refTemplateOptions" />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit">
            {{ t["保存"] }}
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      v-model:visible="newTemplate.show"
      :title="t['复制模板']"
      :footer="false"
      width="400px"
    >
      <div class="my-3">
        <a-input
          v-model="newTemplate.rename"
          size="large"
          :placeholder="t['请输入模板名称']"
        ></a-input>
        <a-button
          size="large"
          type="primary"
          class="w-full mt-3"
          :disabled="newTemplate.rename.length === 0"
          @click="submit"
        >
          {{ t["确定"] }}
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { listResolution } from "@/api/service/resolution/resolution";
import {
  copyTemplate,
  delTemplate,
  getTemplate,
  listTemplate,
  refOptions,
  updateTemplate
} from "@/api/service/template/template";
import { ITemplate } from "@/api/service/template/types";

import { Message, SelectOptionData } from "@arco-design/web-vue";

import { deviceColorList, isList, lightColor } from "@/data/options/selection";
import { ENUM_DATA_SCOPE, ENUM_MAJOR } from "@/enum/system.enum";

import { defaultTemplateParamsOptions } from "@/data/options/options";
import { IQuery } from "@/interface/IAxios";
import { copyText } from "@/utils/utils";
import { useRouter } from "vue-router";
import { columns } from "./columns";
import DynamicField from "./components/DynamicField.vue";
import { getResolution, resolutionList } from "./data";
import { form, majorList, resetForm } from "./form";

const newTemplate = ref({
  show: false,
  rename: "",
  id: ""
});
const router = useRouter();
const t = translate("公共模块");
const loading = ref(true);
const queryObject: IQuery = {
  pageSize: 20,
  pageNum: 1,
  templateName: "",
  resolutionId: "",
  total: 0,
  orderByColumn: "template_id",
  isAsc: "desc",
  scope: ENUM_DATA_SCOPE.THIS_SHOP
};
const query = ref<IQuery>({
  ...queryObject
});

const tableData = ref();
const modelBox = ref(false);
const refTemplateOptions = ref<SelectOptionData[]>([]);
const ratioList = ref<Array<SelectOptionData>>([]);

const getResult = (code: number, msg: string) => {
  if (code === 200) {
    Message.success(msg);
    newTemplate.value.show = false;
    newTemplate.value.id = "";
    newTemplate.value.rename = "";
  } else {
    Message.warning(msg);
  }
};
const getTemplateOptions = async (id: string) => {
  if (form.value.templateId) {
    const { data } = await refOptions(id);
    refTemplateOptions.value = data;
  }
};

const getList = () => {
  loading.value = true;
  listTemplate(query.value).then((res) => {
    query.value.total = res.total;
    loading.value = false;
    tableData.value = res.rows.map((e: any) => {
      e.imgSrc = `${e.imgSrc}?r=${Math.random().toFixed(6)}`;
      if (!e.templateList) {
        e.templateList = form.value.templateList;
      }
      return e;
    });
    columns.forEach((item) => {
      if (item.dataIndex === "resolutionDesc" && item.filterable) {
        item.filterable.filter = null as any;

        item.filterable.filters = ratioList.value.map((item: any) => {
          return {
            text: item.label,
            value: item.value
          };
        });
      }
    });
  });
};
/*  */
function pageChange(index: number) {
  query.value.pageNum = index;
  getList();
}
/* 编辑模板 */
const editTemplate = async (record: ITemplate) => {
  let { data } = await getTemplate(record.templateId!);
  data.light = `${data.light}`;
  form.value = data;
  if (!record.templateList || record.templateList.length === 0) {
    form.value.templateList = defaultTemplateParamsOptions;
  } else {
    form.value.templateList = record.templateList;
  }
  await getTemplateOptions(record.templateId!);
  getResolution();
  modelBox.value = true;
};
/* 已经选择的值 */
const selectedKeys = ref([]);

onMounted(async () => {
  /* 价签尺寸列表 */
  const result = await listResolution();

  ratioList.value = result.rows.map((item: any) => {
    return {
      label: item.description,
      value: item.resolutionId
    };
  });
  ratioList.value.unshift({
    label: t.value?.["所有"],
    value: ""
  });
  getList();
});

/* 保存或者更新 */
async function saveOrUpdate() {
  await updateTemplate(form.value);
  modelBox.value = false;
  resetForm();
  getList();
}

/* 删除选中的项目 */
async function delSelectItems(id: string) {
  let list = [];
  if (id) {
    list = [id];
  } else {
    list = selectedKeys.value;
  }
  await delTemplate(list);
  resetForm();
  getList();
}

const draw = (item?: ITemplate) => {
  if (item) {
    router.push({
      path: "/paint",
      query: {
        id: item.templateId
      }
    });
  } else {
    router.push({
      path: "/paint"
    });
  }
};

const copy = async (id: string) => {
  newTemplate.value.id = id;
  newTemplate.value.show = true;
  getList();
};

const submit = async () => {
  const result = await copyTemplate({
    copyList: [newTemplate.value.id],
    rename: newTemplate.value.rename
  });
  getResult(result.code, result.msg);
  resetForm();
  getList();
  newTemplate.value.id = "";
  newTemplate.value.show = false;
};
const pageSizeChange = (size: number) => {
  query.value.pageSize = size;
  getList();
};

const search = () => {
  query.value.pageNum = 1;
  getList();
};

const filterChange = (dataIndex: string, filteredValues: string[]) => {
  if (dataIndex === "resolutionDesc") {
    dataIndex = "resolutionId";
  }
  query.value.pageNum = 1;

  query.value[dataIndex] = filteredValues[0];
  getList();
};
</script>
